import users.tools.aes as aes
import time
import json
from DataPlatform.settings import SECRET_KEY
from functools import wraps
from django.shortcuts import redirect
from django.http import JsonResponse
from users.models import Users
from users.tools.auth import EXP_TIME_OF_HOUR


def get_ip(q):
    x_forwarded_for = q.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]  # 所以这里是真实的ip
    else:
        ip = q.META.get('REMOTE_ADDR')  # 这里获得代理ip
    return ip


def get_key():
    return SECRET_KEY[:16]


def generate_session(request):
    session_content = {
        'time': time.time(),
        'ip': get_ip(request)
    }
    j_session = json.dumps(session_content)
    session = aes.encrypt(get_key(), j_session)
    return session


def check_session(request):
    who, auth, current_s_id = request.COOKIES.get('who'), request.COOKIES.get('auth'), request.COOKIES.get('sessionid')
    if not (who or auth or current_s_id):
        return False
    his_user_id = request.session.get(who)
    his_s_id = Users.objects.get(account=who).session_id

    # print(request.session.keys(), request.session.values())
    # print(his_user_id, auth)
    # print(his_user_id == auth)
    # 检查cookie与session值非空且相等，同时并非过期
    # print('who--->', who)
    # print('auth--->', auth)
    # print('his_user_id--->', his_user_id)
    # print('current_s_id--->', current_s_id)
    # print('his_s_id--->', his_s_id)
    # print(request.session['_session_expiry'])

    # print(his_user_id, auth, current_s_id, his_s_id)
    return his_user_id and auth and his_user_id == auth and check_session_time(his_user_id) and current_s_id == his_s_id


def check_session_time(session):
    if not session:
        return False
    session = aes.decrypt(get_key(), session)
    try:
        j_content = json.loads(session)
        if time.time() - j_content['time'] > 60 * 60 * EXP_TIME_OF_HOUR:
            return False
        else:
            return True
    except Exception as e:
        repr(e)
        return False


def session_check(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print(args)
        print(kwargs)
        if check_session(args[0]):
            return func(*args, **kwargs)
        else:
            if args[0].method == 'GET':
                return redirect('/users?authCheck=true')
            elif args[0].method == 'POST':
                result = {
                    'code': 505,
                    'msg': '鉴权失败'
                }
                return JsonResponse(result)

    return wrapper
